DECLARE @COUNT INT = 4
DELETE FROM SME_TRANSACTION
WHILE @COUNT > 0
BEGIN
DECLARE @TDATE_FIRST VARCHAR(8)=(SELECT CONVERT(NVARCHAR(8), DATEADD(M,-@COUNT,DATEADD(D,1,MAX_DATE_ENDMONTH)),112) FROM SMES360CUSTOMERDEGREE.DBO.DATE_EM_REPORT)
DECLARE @TDATE_LAST VARCHAR(8) = (SELECT CONVERT(NVARCHAR(8), DATEADD(D, -1, DATEADD(M,1, @TDATE_FIRST)),112))
--print @TDATE_FIRST
--print @TDATE_LAST

DECLARE @STRMONTH NVARCHAR(6) = CONVERT(NVARCHAR(6), @TDATE_FIRST,112)
EXEC ('IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE NAME = ''TRANSACTION_'+@STRMONTH+''' AND TYPE = ''U'')
      BEGIN
	  SELECT * 
		INTO TRANSACTION_'+@STRMONTH+'
		FROM SERVER16.[VPB_WHR2].[DBO].[TBL_VPB_STMT_ENTRY] A
		WHERE CONVERT(DATE,BOOKING_DATE) BETWEEN '''+@TDATE_FIRST+''' AND '''+@TDATE_LAST+'''	      
		                  
		SELECT A.*,B.INITIATION 
		INTO SME_TRANSACTION_'+@STRMONTH+'
		FROM TRANSACTION_'+@STRMONTH+' A
		LEFT JOIN SMES360CUSTOMERDEGREE.[DBO].[TRANSACTION_CODE] B--DATA.DBO.TRANSACTION_CODE_ACTIVE B
		ON A.[TRANSACTION_CODE]=B.ID
		WHERE CUSTOMER_ID IN (SELECT RECID FROM SERVER74.BICDATA.DBO.CUSTOMER WHERE SEGMENT=''SMES'')
	  END

	INSERT SME_TRANSACTION
	SELECT CONVERT(NVARCHAR(6), BOOKING_DATE, 112) AS YEARMONTH, * FROM SME_TRANSACTION_'+@STRMONTH+'
')
SET @COUNT = @COUNT -1
END